import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/services/index.dart';
import '../../../common/routers/index.dart';

/// 一起玩页面控制器
/// 
/// 负责：
/// - 活动列表管理
/// - 下拉刷新和上拉加载
class ActivityIndexController extends GetxController {
  ActivityIndexController();

  // ==================== 服务依赖 ====================
  final UserService _userService = Get.find<UserService>();
  
  // ==================== 活动列表 ====================
  final activities = <ActivityEntity>[].obs;
  final isLoading = false.obs;
  final isLoadingMore = false.obs;
  final hasMoreActivities = true.obs;
  
  // 分页参数
  int currentPage = 1;
  final int pageSize = 20;
  
  // 位置参数（默认武汉）
  final double latitude = 30.5928;
  final double longitude = 114.3055;
  final double radius = 50.0;

  @override
  void onReady() {
    super.onReady();
    _initData();
  }
  
  // ==================== 初始化 ====================
  
  void _initData() {
    // 加载活动列表
    loadActivities();
  }
  
  // ==================== 活动列表 ====================
  
  /// 加载活动列表
  Future<void> loadActivities({bool isRefresh = false}) async {
    if (isLoading.value) return;
    
    if (isRefresh) {
      currentPage = 1;
      hasMoreActivities.value = true;
    }
    
    isLoading.value = true;
    
    try {
      debugPrint('🎯 加载活动列表 - 页码: $currentPage');
      
      final result = await ActivityApi.getNearbyActivities(
        latitude: latitude,
        longitude: longitude,
        radius: radius,
        limit: pageSize,
        page: currentPage,
        sortBy: 'time',      // 🔥 按时间排序
        order: 'desc',       // 🔥 降序（最新的在前面）
      );
      
      if (result.isSuccess) {
        if (isRefresh) {
          activities.value = result.activities;
        } else {
          activities.addAll(result.activities);
        }
        
        // 判断是否还有更多数据
        hasMoreActivities.value = result.activities.length >= pageSize;
        
        debugPrint('✅ 活动列表加载成功 - 数量: ${result.activities.length}');
        
        // 🔥 前端排序：按时间降序（最新的在前面）
        _sortActivitiesByTime();
      } else {
        debugPrint('❌ 活动列表加载失败: ${result.message}');
      }
    } catch (e) {
      debugPrint('❌ 活动列表加载异常: $e');
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 加载更多活动
  Future<void> loadMoreActivities() async {
    if (isLoadingMore.value || !hasMoreActivities.value) {
      if (!hasMoreActivities.value) {
        debugPrint('⚠️ 没有更多活动了');
      }
      return;
    }
    
    isLoadingMore.value = true;
    currentPage++;
    
    try {
      debugPrint('📥 加载更多活动 - 页码: $currentPage');
      
      final result = await ActivityApi.getNearbyActivities(
        latitude: latitude,
        longitude: longitude,
        radius: radius,
        limit: pageSize,
        page: currentPage,
        sortBy: 'time',      // 🔥 按时间排序
        order: 'desc',       // 🔥 降序（最新的在前面）
      );
      
      if (result.isSuccess) {
        activities.addAll(result.activities);
        hasMoreActivities.value = result.activities.length >= pageSize;
        
        debugPrint('✅ 更多活动加载成功 - 数量: ${result.activities.length}');
        
        // 🔥 前端排序：按时间降序（最新的在前面）
        _sortActivitiesByTime();
        
        if (!hasMoreActivities.value) {
          debugPrint('⚠️ 已加载全部活动');
        }
      } else {
        currentPage--; // 失败时回退页码
        debugPrint('❌ 更多活动加载失败: ${result.message}');
      }
    } catch (e) {
      currentPage--; // 异常时回退页码
      debugPrint('❌ 更多活动加载异常: $e');
    } finally {
      isLoadingMore.value = false;
    }
  }
  
  /// 🔄 活动列表排序（按时间降序，最新的在前面）
  void _sortActivitiesByTime() {
    activities.sort((a, b) {
      // 🔥 按发布时间排序（新的排前面）
      if (a.activityPublishTime != null && b.activityPublishTime != null) {
        try {
          final timeA = DateTime.parse(a.activityPublishTime!);
          final timeB = DateTime.parse(b.activityPublishTime!);
          return timeB.compareTo(timeA); // 降序（新的排前面）
        } catch (e) {
          debugPrint('⚠️ 时间解析失败: $e');
          return 0;
        }
      }
      
      // 如果时间为空，放到最后
      if (a.activityPublishTime == null) return 1;
      if (b.activityPublishTime == null) return -1;
      
      return 0;
    });
    
    debugPrint('✅ 前端排序完成（按时间降序）');
    
    // 打印前5个活动的时间
    if (activities.isNotEmpty) {
      debugPrint('📊 排序后前5个活动（按时间）:');
      for (var i = 0; i < activities.length && i < 5; i++) {
        final activity = activities[i];
        debugPrint('   ${i + 1}. ${activity.activityTitle} - ${activity.activityPublishTime}');
      }
    }
  }
  
  // ==================== 活动操作 ====================
  
  /// 查看活动详情
  void viewActivity(int activityId) {
    debugPrint('👁️ 查看活动详情 - ID: $activityId');
    
    // 查找活动对象
    ActivityEntity? activity;
    activity = activities.firstWhereOrNull((a) => a.activityId == activityId);
    
    // 跳转到活动详情页
    Get.toNamed(
      RouteNames.activityActivityDetial,
      arguments: {
        'activityId': activityId,
        'activity': activity?.toJson(), // 传递完整活动对象（如果存在）
        'fromPage': 'activity_index',
      },
    );
  }
}
